package io.github.wanggit.antcms.server.web;

import io.github.wanggit.antcms.server.domain.AntCatalog;
import io.github.wanggit.antcms.server.dto.CatalogDTO;
import io.github.wanggit.antcms.server.service.CatalogService;
import io.github.wanggit.antcms.server.web.utils.TreeNodeUtil;
import io.github.wanggit.antcms.server.web.vm.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
@RequestMapping("catalog")
public class CatalogController {

    @Autowired private CatalogService catalogService;

    @GetMapping("list")
    public Result listCatalog() {
        List<AntCatalog> catalogs = catalogService.list();
        List<CatalogDTO> catalogDTOS =
                catalogs.stream().map(CatalogDTO::from).collect(Collectors.toList());
        TreeNodeUtil treeNodeUtil = new TreeNodeUtil(catalogDTOS);
        List<CatalogDTO> treeNodes = treeNodeUtil.treePreOrders();
        return Result.ok(treeNodes);
    }

    @PostMapping("sou")
    public Result saveOrUpdateCatalog(@RequestBody AntCatalog catalog) {
        catalogService.saveOrUpdateCatalog(catalog);
        return Result.ok();
    }

    @GetMapping("del")
    public Result deleteCatalog(@RequestParam("id") Long id) {
        catalogService.deleteCatalog(id);
        return Result.ok();
    }

    @GetMapping("detail")
    public Result detailCatalog(@RequestParam("id") Long id) {
        return Result.ok(catalogService.getById(id));
    }
}
